<?php

namespace App\Listeners;

use Laravel\Octane\Events\RequestReceived;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Laravel\Octane\Facades\Octane;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class WebSocketHandshakeListener
{
    /**
     * Create the event listener.
     */
    public function handle($event): void
    {
        $request = $event->request;
        // 手动创建 Response 对象
        $response = new Response($request->fd);

        if ($this->isWebSocketHandshake($request)) {
            $this->performHandshake($request, $response);
            $this->recordConnection($request->fd);

            // 标记请求已处理
            $event->handled = true;
        }
    }

    private function isWebSocketHandshake($request): bool
    {
        return $request->server['request_uri'] === '/ws'
            && isset($request->header['upgrade'])
            && strtolower($request->header['upgrade']) === 'websocket';
    }

    private function performHandshake($request, $response): void
    {
        $key = $request->header['sec-websocket-key'];
        $response->header('Upgrade', 'websocket');
        $response->header('Connection', 'Upgrade');
        $response->header('Sec-WebSocket-Accept', base64_encode(sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)));
        $response->status(101);
        $response->end();
    }

    private function recordConnection(int $fd): void
    {
        Octane::table('websocket_connections')->set($fd, [
            'fd' => $fd,
        ]);
    }
}
